/**
 * 基础菜单 商品管理
 */
<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>材料管理</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 搜索筛选 -->
    <el-form :inline="true" :model="condition" class="user-search">
      <el-form-item label="搜索：">
        <el-input
          size="small"
          v-model="condition.name"
          placeholder="输入材料名称"
        ></el-input>
      </el-form-item>

      <el-form-item label="">
        <el-select
          size="small"
          v-model="condition.type"
          placeholder="请选择材料类型"
        >
          <el-option label="类型" value=""></el-option>
          <el-option
            v-for="(item, index) in types"
            :key="index"
            :label="item.name"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="">
        <el-select
          size="small"
          v-model="condition.status"
          placeholder="请选择材料状态"
        >
          <el-option label="状态" value=""></el-option>
          <el-option label="正常" value="01"></el-option>
          <el-option label="已冻结" value="00"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button
          size="small"
          type="primary"
          icon="el-icon-search"
          @click="search"
          >搜索</el-button
        >
        <el-button
          size="small"
          type="primary"
          icon="el-icon-plus"
          @click="handleEdit('add')"
          >添加</el-button
        >
      </el-form-item>
    </el-form>
    <!--列表-->

    <div>
      <el-button
        size="mini"
        type="danger"
        @click="dels"
        style="margin-bottom: 5px"
        >批量删除</el-button
      >
    </div>

    <el-table
      size="small"
      :data="listData"
      @selection-change="selectChange"
      highlight-current-row
      v-loading="loading"
      border
      element-loading-text="拼命加载中"
      style="width: 100%"
    >
      <el-table-column align="center" type="selection" width="60">
      </el-table-column>
      <el-table-column sortable prop="iconUrl" label="样图" min-width="150">
        <template slot-scope="scope">
          <el-image
            style="width: 100px; height: 100px"
            :src="scope.row.iconUrl"
            fit="fit"
          ></el-image>
        </template>
      </el-table-column>
      <el-table-column sortable prop="name" label="材料名称" min-width="150">
      </el-table-column>
      <el-table-column sortable prop="type" label="材料类型" min-width="150" :formatter="typeFormat">
      </el-table-column>
      <el-table-column
        sortable
        prop="purchasePrice"
        label="进价"
        min-width="150"
      >
      </el-table-column>
      <el-table-column sortable prop="price" label="售价" min-width="150">
      </el-table-column>
      <el-table-column
        sortable
        prop="createTime"
        label="创建时间"
        min-width="150"
      >
      </el-table-column>
      <el-table-column
        sortable
        prop="updateTime"
        label="修改时间"
        min-width="150"
      >
      </el-table-column>

       <el-table-column prop="status" label="状态" min-width="80">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            active-value="01"
            inactive-value="00"
            active-color="#13ce66"
            inactive-color="#ff4949"
            @change="setStatus(scope.row.id, scope.row.status)"
          >
          </el-switch>
        </template>
      </el-table-column>

      <el-table-column align="center" label="操作" min-width="300">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="success"
            @click="handleEdit('view', scope.row)"
            >详情</el-button
          >

          <el-button size="mini" @click="handleEdit('edit', scope.row)"
            >编辑</el-button
          >
          <el-button
            size="mini"
            type="danger"
            @click="del( scope.row.id)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <Pagination
      v-bind:child-msg="pageparm"
      @callFather="callFather"
    ></Pagination>
    <!-- 编辑界面 -->
    <el-dialog
      :title="title"
      :visible.sync="editFormVisible"
      width="50%"
      @close="closeDialog"
    >
      <el-form
        label-width="100px"
        :model="editForm"
        :rules="rules"
        ref="editForm"
      >
        <el-row>
          <el-col :span="12">
              <el-form-item label="材料名称" prop="name" >
                <el-input
                  size="small"
                  v-model="editForm.name"
                  auto-complete="off"
                  placeholder="请输入材料名称"
                  :disabled="isView"
                ></el-input>
              </el-form-item>
              
              <el-form-item label="材料类型" prop="type">
              <el-select  size="small"
                  v-model="editForm.type"
                  placeholder="请选择材料类型"
                  :disabled="isView"
                  >
                <el-option v-for="(item,index) in types" :key="index" :label="item.name" :value="item.value"></el-option>
              </el-select>
              </el-form-item>

              <el-form-item label="进价" prop="purchasePrice">
                <el-input-number v-model="editForm.purchasePrice" :precision="2" :step="0.1" :disabled="isView"></el-input-number>
              </el-form-item>

              <el-form-item label="售价" prop="price">
              <el-input-number v-model="editForm.price" :precision="2" :step="0.1" :disabled="isView" ></el-input-number>
              </el-form-item>

              <el-form-item label="描述" prop="remarks">
                <el-input type="textarea" v-model="editForm.remarks" placeholder="请输入该物品的描述" :rows="3" :disabled="isView"></el-input>
              </el-form-item>
          </el-col>

          <el-col :span="12">
           <el-form-item>
              <el-upload
              class="avatar-uploader"
              action="http://127.0.0.1:8090/material/images"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
              :disabled="isView"
              >
              <img v-if="editForm.iconUrl" :src="editForm.iconUrl" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
           </el-form-item>
          </el-col>
        </el-row>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="closeDialog">取消</el-button>
        <el-button
          size="small"
          type="primary"
          :loading="loading"
          class="title"
          @click="submitForm('editForm')"
          >保存</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Pagination from "../../components/Pagination";
import dataOrigin from "../../assets/data.json";
export default {
  inject: ["reload"],
  data() {
    
    return {
      loading: false, //是显示加载
      editFormVisible: false, //控制编辑页面显示与隐藏
      isView:false, //是否为详情页面
      isAdd:false, //是否为添加页面
      title: "添加",
      types: dataOrigin.materialTypes,
      editForm: {
        id: "",
        name: "",
        iconUrl: "",
        type: "",
        purchasePrice:"",
        price:"",
        remarks: "",
        status: "",
      },
      // rules表单验证
      rules: {
        name: [
          { required: true, message: "请输入材料名称", trigger: "blur" },
        ],
        type: [
          { required: true, message: "请选择材料类型", trigger: "blur" },
        ],
        purchasePrice: [
          { required: true, message: "请输入进价价格", trigger: "blur" },
        ],
        price: [
          { required: true, message: "请输售价价格", trigger: "blur" },
        ],
      },
      condition: {
        currentPage: 1,
        pageSize: 10,
        name: "",
        type: "",
        status: "",
      },
      listData: [], //用户数据
      // 选择数据
      selectdata: [],
      // 分页参数
      pageparm: {
        currentPage: 1,
        pageSize: 10,
        total: 0,
      },
    };
  },
  // 注册组件
  components: {
    Pagination,
  },

  /**
   * 创建完毕
   */
  created() {
    this.init();
  },

  /**
   * 里面的方法只有被调用才会执行
   */
  methods: {
    //初始化表格
    async init() {
      this.loading = true;
      var d = await this.$axios.post("/material/page",this.condition);
      if(d.code==200){
        this.listData = d.data.records;
        this.pageparm.currentPage = d.data.current;
        this.pageparm.pageSize = d.data.size;
        this.pageparm.total = d.data.total;
      }else{
        this.$message.error(d.message);
      }
      this.loading = false;
    },

     //修改用户状态
    async setStatus(id, status) {
      this.loading = true;
      let param = {
        id: id,
        status: status,
      };
      var d = await this.$axios.put("/material/status", param);
      if (d.code == 200) {
        this.$message.success(d.message);
      } else {
        this.$message.error(d.message);
      }
      this.loading = false;
    },

    //类型格式化
    typeFormat(row,column,cellValue,index){
      for (let i = 0; i < this.types.length; i++) {
        if(cellValue == this.types[i].value){
          return this.types[i].name
        }
      }
      return "未知错误"
    },

    // 分页插件事件
    callFather(parm) {
      this.condition.currentPage = parm.currentPage;
      this.condition.pageSize = parm.pageSize;
      this.init();
    },
    // 搜索事件
    search() {
      this.init();
    },

    //显示编辑界面
    handleEdit: function (name, row) {
      this.editFormVisible = true;
      if (row != undefined && row != "undefined") {
        this.title = "修改";
        this.isAdd = false;
        this.isView = name=="view";
        this.editForm.id = row.id;
        this.editForm.name = row.name;
        this.editForm.type = row.type;
        this.editForm.purchasePrice = row.purchasePrice;
        this.editForm.price = row.price;
        this.editForm.iconUrl = row.iconUrl;
        this.editForm.remarks = row .remarks;
      } else {
        this.title = "添加";
        this.isAdd = true;
        this.isView = false;
      }
    },

    // 编辑、增加页面保存方法
    submitForm(editData) {
      this.$refs[editData].validate(async (valid) => {
        if (valid) {
          if(this.isAdd){
            //添加            
            var  d = await this.$axios.post("/material/add",this.editForm)
            if(d.code == 200){
              this.$message.success(d.message)
              this.reload();
            }else{
              this.$message.error(d.message)
            }
            
          }else{
            //编辑
            var  d = await this.$axios.put("/material/update",this.editForm)
            if(d.code == 200){
              this.$message.success(d.message)
              this.reload();
            }else{
              this.$message.error(d.message)
            }
          }
        } else {
          return false;
        }
      });
    },

    // 删除
      del(id) {
      this.$confirm("确定要删除吗?", "信息", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          this.loading = true
          var d = await this.$axios.delete("/material/del/"+id)
          if(d.code ==200){
            this.$message.success(d.message)
             this.loading = false
            this.reload();
          }else{
            this.$message.error(d.message)
             this.loading = false
          } 
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    // 选择复选框事件
    selectChange(val) {
      this.selectdata = val;
    },

     // 批量删除
      dels() {
         if(this.selectdata.length<=0){
          return;
        }
      this.$confirm("确定要删除吗?", "信息", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          this.loading = true
          let ids = [];
            for (let i = 0; i < this.selectdata.length; i++) {
              ids.push(this.selectdata[i].id);
            }
          var d = await this.$axios.post("/material/dels",ids)
          if(d.code ==200){
            this.$message.success(d.message)
             this.loading = false
            this.reload();
          }else{
            this.$message.error(d.message)
             this.loading = false
          } 
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    //图片上传成功时
    handleAvatarSuccess(res, file) {
        this.editForm.iconUrl = res.message
    },

    //图片上传前(图片大小限制)
    beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg';
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        return isJPG && isLt2M;
      },

    // 关闭编辑、增加弹出框
    closeDialog() {
      this.editFormVisible = false;
      this.$refs.editForm.resetFields();
      this.editForm.iconUrl = '';
    },
  },
};
</script>

<style scoped>
.user-search {
  margin-top: 20px;
}
.userRole {
  width: 100%;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

 
 